package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.fadan.CardContent;
import com.uzai.common.dto.fadan.FollowMsgDto;
import com.uzai.common.dto.fadan.FollowQfMsgDto;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.common.enums.MessageTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.RandomUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.tiktok.group.tiktokgroup.TiktokConversationIdDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsTiktokConversation;
import com.uzai.console.jsonvo.fd.fdtemplate.FdTemplateData;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdSendJobSyncService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.fd.FdFollowSendService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.tiktok.TiktokConversationService;
import com.uzai.console.vo.fd.fdfollowconfigqfkeyword.FdFollowConfigQfKeywordVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发单跟发发送
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdFollowSendServiceImpl implements FdFollowSendService {

    Logger logger = LoggerFactory.getLogger(FdFollowSendServiceImpl.class);

    @Autowired
    private FdFollowConfigMapper fdFollowConfigMapper;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private FdDevicePlanGroupMapper fdDevicePlanGroupMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private FdSendJobSyncService fdSendJobSyncService;
    @Autowired
    private FdSendJobMapper fdSendJobMapper;
    @Autowired
    private FdFollowConfigQfKeywordMapper fdFollowConfigQfKeywordMapper;
    @Autowired
    private FdFollowConfigQfGroupTuoMapper fdFollowConfigQfGroupTuoMapper;
    @Autowired
    private FdFollowConfigQfGroupMapper fdFollowConfigQfGroupMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private TiktokConversationService tiktokConversationService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 跟发发单发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void followSendFd(FollowMsgDto followMsgDto, FdFollowConfig fdFollowConfig){

        if(fdFollowConfig == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    followMsgDto.getMerId(), 0, null,
                    "",0L,
                    "跟发配置不存在")));
            return;
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdFollowConfig.getDeviceUniqueId(), null , fdFollowConfig.getMerId());
        if(device == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    fdFollowConfig.getMerId(), 0, fdFollowConfig.getDeviceUniqueId(),
                    "",0L,
                    "跟发机器人不存在")));
            return;
        }

        if(fdFollowConfig.getFdDevicePlanId() == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                    "",0L,
                    "请选择设备方案")));
            return;
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdFollowConfig.getFdDevicePlanId(), fdFollowConfig.getMerId());
        if(fdDevicePlan == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                    "",0L,
                    "请选择设备方案")));
            return;
        }

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if(fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                    "",0L,
                    "设备方案未配置任何群信息")));
            return;
        }

        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
            if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), fdFollowConfig.getMerId(), device.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if(wxgroup_manageplan_id == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群还未配置管理方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId())));
                    return;
                }
                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxgroup_manageplan_id, fdDevicePlan.getMerId());
                if(configPlan == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId())));
                    return;
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdDevicePlan.getMerId());
                if(sysPlugin == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId())));
                    return;
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案保存的数据格式错误")));
                    return;
                }

                if(jsonObject == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息，群wxid为："+fdDevicePlanGroup.getWxid()+"；群内机器人唯一id为：" + fdDevicePlanGroup.getDeviceUniqueId())));
                    return;
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案未开启社群群发功能")));
                    return;
                }
            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), fdDevicePlanGroup.getMerId(), fdDevicePlanGroup.getDeviceId(), fdDevicePlanGroup.getWxid());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if(wxworkgroup_manageplan_id == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群还未配置管理方案")));
                    return;
                }

                ConfigPlan configPlan = configPlanMapper.selectById((Long)wxworkgroup_manageplan_id, fdFollowConfig.getMerId());
                if(configPlan == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案")));
                    return;
                }

                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdFollowConfig.getMerId());
                if(sysPlugin == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息")));
                    return;
                }

                JSONObject jsonObject = null;

                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案保存的数据格式错误")));
                    return;
                }

                if(jsonObject == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息")));
                    return;
                }

                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案未开启社群群发功能")));
                    return;
                }
            }else if(fdDevicePlanGroup.getDeviceType().equals(DeviceTypeEnum.TIKTOK.getKey())){//抖音设备
                TiktokConversationIdDto tiktokConversationIdDto = new TiktokConversationIdDto();
                tiktokConversationIdDto.setMerId(fdFollowConfig.getMerId());
                tiktokConversationIdDto.setId(fdDevicePlanGroup.getGroupId());
                EsTiktokConversation esTiktokConversation  = tiktokConversationService.findTiktokConversationInfo(tiktokConversationIdDto);
                if(esTiktokConversation == null || Tools.getLong(esTiktokConversation.getManagePlanId()) == 0 ){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群还未配置管理方案")));
                    return;
                }
                ConfigPlan configPlan = configPlanMapper.selectById(esTiktokConversation.getManagePlanId(), fdFollowConfig.getMerId());
                if(configPlan == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案")));
                    return;
                }
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdFollowConfig.getMerId());
                if(sysPlugin == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息")));
                    return;
                }
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(sysPlugin.getData());
                }catch (Exception e){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案保存的数据格式错误")));
                    return;
                }
                if(jsonObject == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群未找到配置方案对应插件信息")));
                    return;
                }
                Integer fdSwitch = jsonObject.getInteger("fdSwitch");
                if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                            "",0L,
                            "该群管理方案未开启社群群发功能")));
                    return;
                }
            }
        }

        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = new ArrayList<>();
        FdTemplateData fdTemplateData = new FdTemplateData();
        fdTemplateData.setMsgType(followMsgDto.getMsgType());
        fdTemplateData.setGap(0);
        if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_TEXT.getValue().intValue()){//文本
            fdTemplateData.setContent(followMsgDto.getContent());
        }else if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_IMAGE.getValue().intValue()){//普通图片
            fdTemplateData.setImgUrl(followMsgDto.getContent());
            fdTemplateData.setImgType(1);
        }else if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_VIDEO.getValue().intValue()){ //视频
            fdTemplateData.setVideoUrl(followMsgDto.getContent());
        }else if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_GIF_IMAGE.getValue().intValue()){ //gif图片
            fdTemplateData.setImgUrl(followMsgDto.getContent());
            fdTemplateData.setImgType(2);
        }else if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_URL_CARD.getValue().intValue() || followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_APP_CARD.getValue().intValue()){ //卡片或者分享卡片
            fdTemplateData.setMsgType(MessageTypeEnum.MT_URL_CARD.getValue().intValue());
            CardContent card = followMsgDto.getCard();
            if(card != null){
                fdTemplateData.setCardTitle(card.getTitle());
                fdTemplateData.setCardDes(card.getDescribe());
                fdTemplateData.setCardImg(card.getImageStr());
                fdTemplateData.setCardUrl(card.getUrl());
            }
        }else if(followMsgDto.getMsgType().intValue() == MessageTypeEnum.MT_WEAPP_CARD.getValue().intValue()){ //小程序
            CardContent card = followMsgDto.getCard();
            if(card != null){
                fdTemplateData.setMiniProAppId(card.getAppId());
                fdTemplateData.setMiniProTitle(card.getTitle());
                fdTemplateData.setMiniProDesc(card.getDescribe());
                fdTemplateData.setMiniProUrl(card.getPagePath());
                fdTemplateData.setMiniImgPwdStr(card.getImageStrKey());
                fdTemplateData.setMiniImgStr(card.getImageStr());
                fdTemplateData.setMiniProGhId(card.getSourceId());
                fdTemplateData.setMiniProName(card.getDisplayName());
            }
        }else{
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                    "",0L,
                    "跟发消息类型不支持此种类型，type=" +followMsgDto.getMsgType())));
            return;
        }


        //关键词过滤
        String ignore = fdFollowConfig.getIgnore();
        if(StringUtils.isNotBlank(ignore)){
            try {
                List<String> ignoreList = JSONObject.parseArray(ignore, String.class);
                if(ignoreList != null && ignoreList.size() > 0){
                    for (String ignoreKey : ignoreList){
                        //文本
                        if(Tools.getStr(fdTemplateData.getContent()).contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                                    "",0L,
                                    "关键词过滤，内容为：" +fdTemplateData.getContent()+"；关键词："+ignoreKey)));
                            return;
                        }
                        //卡片标题
                        if(Tools.getStr(fdTemplateData.getCardTitle()).contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                                    "",0L,
                                    "关键词过滤，内容为：" +fdTemplateData.getContent()+"；关键词："+ignoreKey)));
                            return;
                        }
                        //卡片描述
                        if(Tools.getStr(fdTemplateData.getCardDes()).contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                                    "",0L,
                                    "关键词过滤，内容为：" +fdTemplateData.getContent()+"；关键词："+ignoreKey)));
                            return;
                        }

                        //小程序标题
                        if(Tools.getStr(fdTemplateData.getMiniProTitle()).contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                                    "",0L,
                                    "关键词过滤，内容为：" +fdTemplateData.getContent()+"；关键词："+ignoreKey)));
                            return;
                        }

                        //小程序描述
                        if(Tools.getStr(fdTemplateData.getMiniProDesc()).contains(ignoreKey)){
                            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                                    fdFollowConfig.getMerId(), device.getRecvmsgType(), fdFollowConfig.getDeviceUniqueId(),
                                    "",0L,
                                    "关键词过滤，内容为：" +fdTemplateData.getContent()+"；关键词："+ignoreKey)));
                            return;
                        }
                    }
                }
            }catch (Exception e){

            }
        }


        fdTemplateDataList.add(fdTemplateData);
        if(fdTemplateDataList == null || fdTemplateDataList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入发送内容");
        }

        //主任务
        int now = DateUtil.getNowTime();
        FdSendJob fdSendJob_parent = new FdSendJob();
        fdSendJob_parent.setId(IdWorker.getId());
        fdSendJob_parent.setParentId(0L);
        fdSendJob_parent.setMerId(fdFollowConfig.getMerId());
        fdSendJob_parent.setName("跟发消息");
        fdSendJob_parent.setSource(2);//跟发
        fdSendJob_parent.setFdDevicePlanId(fdFollowConfig.getFdDevicePlanId());
        fdSendJob_parent.setStatus(3); //已完成(跟发消息自动完成)
        fdSendJob_parent.setData(JSONObject.toJSONString(fdTemplateDataList));
        fdSendJob_parent.setTotalCount(0);
        fdSendJob_parent.setFinishCount(0);
        fdSendJob_parent.setFinishCountSnapshot(0);
        fdSendJob_parent.setBeginTime(now);
        fdSendJob_parent.setExptime(now + 7 * 24 * 3600);
        fdSendJob_parent.setCreateTime(now);
        fdSendJob_parent.setUpdateTime(now);
        fdSendJob_parent.setBeginTime(now);
        fdSendJob_parent.setSendStartTime(now);
        fdSendJobMapper.insertSelective(fdSendJob_parent);

        //封装子任务
        //封装所有群(子任务)
        List<FdSendJob> fdSendJobList_sub = new ArrayList<>();
        for (FdDevicePlanGroup fdDevicePlanGroup : fdDevicePlanGroupList) {
            FdSendJob fdSendJob_sub = new FdSendJob();
            fdSendJob_sub.setId(IdWorker.getId());
            fdSendJob_sub.setParentId(fdSendJob_parent.getId());
            fdSendJob_sub.setMerId(fdSendJob_parent.getMerId());
            fdSendJob_sub.setName(fdSendJob_parent.getName());
            fdSendJob_sub.setSource(fdSendJob_parent.getSource());
            fdSendJob_sub.setFdDevicePlanId(fdSendJob_parent.getFdDevicePlanId());
            fdSendJob_sub.setStatus(3); //已完成(跟发消息自动完成)
            fdSendJob_sub.setData(fdSendJob_parent.getData());
            fdSendJob_sub.setTotalCount(0);
            fdSendJob_sub.setFinishCount(0);
            fdSendJob_sub.setFinishCountSnapshot(0);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setExptime(fdSendJob_parent.getBeginTime() + 15 * 24 * 3600);
            fdSendJob_sub.setCreateTime(now);
            fdSendJob_sub.setUpdateTime(now);
            fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
            fdSendJob_sub.setSendStartTime(fdSendJob_parent.getBeginTime());
            //群发机器人消息
            fdSendJob_sub.setDeviceType(fdDevicePlanGroup.getDeviceType());
            fdSendJob_sub.setGroupId(fdDevicePlanGroup.getGroupId());
            fdSendJob_sub.setNick(fdDevicePlanGroup.getNick());
            fdSendJob_sub.setDeviceUniqueId(fdDevicePlanGroup.getDeviceUniqueId());
            fdSendJob_sub.setDeviceId(fdDevicePlanGroup.getDeviceId());
            fdSendJob_sub.setWxid(fdDevicePlanGroup.getWxid());
            fdSendJob_sub.setGroupSendDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
            fdSendJobList_sub.add(fdSendJob_sub);
        }

        fdSendJobSyncService.followFdSendJobTaskSync(fdTemplateDataList, fdDevicePlan,  fdDevicePlanGroupList, fdSendJobList_sub, fdFollowConfig);
    }

    /**
     * 气氛组跟发发送
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    public void followQfSendFd(FollowQfMsgDto followQfMsgDto, FdFollowConfigQf fdFollowConfigQf){
        if(fdFollowConfigQf == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    fdFollowConfigQf.getMerId(), 0, null,
                    "",0L,
                    "气氛组跟发配置不存在")));
            return;
        }

        if(followQfMsgDto.getDeviceType() == null){
            return;
        }

        DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getById(followQfMsgDto.getDeviceType());
        if(deviceTypeEnum == null ){
            return;
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(followQfMsgDto.getDeviceUniqueId(), deviceTypeEnum.getKey(), followQfMsgDto.getMerId());
        if(device == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    fdFollowConfigQf.getMerId(), 0, followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "气氛组跟发机器人不存在")));
            return;
        }

        //查询匹配关键词
        FdFollowConfigQfKeyword fdFollowConfigQfKeyword = fdFollowConfigQfKeywordMapper.selectByUniqueIndex(fdFollowConfigQf.getMerId(), followQfMsgDto.getFdFollowConfigQfId(), followQfMsgDto.getKeyword());
        if(fdFollowConfigQfKeyword == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    fdFollowConfigQf.getMerId(), 0, followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该配置任务未找到该关键词")));
            return;
        }
        if(StringUtils.isBlank(fdFollowConfigQfKeyword.getReplyInfo())){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    followQfMsgDto.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该关键词未配置回复语")));
            return;
        }

        //查询该机器人脱信息
        FdFollowConfigQfGroupTuo fdFollowConfigQfGroupTuo = fdFollowConfigQfGroupTuoMapper.selectByUniqueIndex(followQfMsgDto.getMerId(), followQfMsgDto.getGroupWxid(), followQfMsgDto.getSendWxid(), device.getDeviceId());
        if(fdFollowConfigQfGroupTuo == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    followQfMsgDto.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该监控机器人未配置气氛组自动跟发任务，群wxid为："+followQfMsgDto.getGroupWxid()+"；机器人wxid为：" + device.getDeviceId())));
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "");
        }

        FdFollowConfigQfGroup fdFollowConfigQfGroup = fdFollowConfigQfGroupMapper.selectById(fdFollowConfigQfGroupTuo.getFdFollowConfigQfGroupId(), fdFollowConfigQfGroupTuo.getMerId());
        if(fdFollowConfigQfGroup == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    followQfMsgDto.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该监控机器人未配置气氛组自动跟发任务，群wxid为："+fdFollowConfigQfGroup.getGroupWxid()+"；机器人wxid为：" + fdFollowConfigQfGroup.getDeviceId())));
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "");
        }


        //判断此群的配置方案是否开启了群发功能，如果未开启，则抛出异常
        if(deviceTypeEnum.getKey().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())){//个人微信
            //缓存中的微信群管理方案key
            String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), fdFollowConfigQfGroupTuo.getMerId(), device.getDeviceId(), fdFollowConfigQfGroupTuo.getGroupWxid());
            Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
            if(wxgroup_manageplan_id == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群还未配置管理方案，群wxid为："+fdFollowConfigQfGroupTuo.getGroupWxid()+"；气氛组机器人唯一id为：" + fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId())));
                return;
            }
            ConfigPlan configPlan = configPlanMapper.selectById((Long)wxgroup_manageplan_id, fdFollowConfigQfGroupTuo.getMerId());

            if(configPlan == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案，群wxid为："+fdFollowConfigQfGroupTuo.getGroupWxid()+"；群内机器人唯一id为：" + fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId())));
                return;
            }

            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdFollowConfigQfGroupTuo.getMerId());
            if(sysPlugin == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案对应插件信息，群wxid为："+fdFollowConfigQfGroupTuo.getGroupWxid()+"；群内机器人唯一id为：" + fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId())));
                return;
            }
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(sysPlugin.getData());
            }catch (Exception e){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群管理方案保存的数据格式错误")));
                return;
            }

            if(jsonObject == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案对应插件信息，群wxid为："+fdFollowConfigQfGroupTuo.getGroupWxid()+"；群内机器人唯一id为：" + fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId())));
                return;
            }

            Integer fdSwitch = jsonObject.getInteger("fdSwitch");
            if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群管理方案未开启社群群发功能")));
                return;
            }
        }else{//企业微信
            //缓存中的企业微信群管理方案key
            String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), fdFollowConfigQfGroupTuo.getMerId(), device.getDeviceId(), fdFollowConfigQfGroupTuo.getGroupWxid());
            Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
            if(wxworkgroup_manageplan_id == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "该群还未配置管理方案")));
                return;
            }

            ConfigPlan configPlan = configPlanMapper.selectById((Long)wxworkgroup_manageplan_id, fdFollowConfigQfGroupTuo.getMerId());
            if(configPlan == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案")));
                return;
            }

            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), fdFollowConfigQfGroupTuo.getMerId());
            if(sysPlugin == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案对应插件信息")));
                return;
            }

            JSONObject jsonObject = null;

            try {
                jsonObject = JSONObject.parseObject(sysPlugin.getData());
            }catch (Exception e){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群管理方案保存的数据格式错误")));
                return;
            }

            if(jsonObject == null){
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群未找到配置方案对应插件信息")));
                return;
            }

            Integer fdSwitch = jsonObject.getInteger("fdSwitch");
            if(fdSwitch == null || fdSwitch.intValue() != 1){ //未开启社群群发功能
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                        fdFollowConfigQfGroupTuo.getMerId(), device.getRecvmsgType(), fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId(),
                        "",0L,
                        "该群管理方案未开启社群群发功能")));
                return;
            }

        }

        FdFollowConfigQfKeywordVo.ReplyInfo replyInfo = null;
        try {
            List<FdFollowConfigQfKeywordVo.ReplyInfo> replyInfoList = JSONObject.parseArray(fdFollowConfigQfKeyword.getReplyInfo(), FdFollowConfigQfKeywordVo.ReplyInfo.class);
            if(replyInfoList != null && replyInfoList.size() > 0){
                //获取此数组内的随机对象
                int random = RandomUtil.getRandomInt(0, replyInfoList.size()-1);
                replyInfo  = replyInfoList.get(random);
            }
        }catch (Exception e){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    followQfMsgDto.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该关键词回复语解析出错")));
            return;
        }

        if(replyInfo == null){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    followQfMsgDto.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "该配置任务未找到回复语")));
            return;
        }

        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = new ArrayList<>();
        FdTemplateData fdTemplateData = new FdTemplateData();
        fdTemplateData.setMsgType(Tools.getInteger(replyInfo.getType()));
        //延迟时间
        //获取最小和最大时间的随机数（秒）
        int rateMax = Tools.getInteger(fdFollowConfigQf.getGapMax());
        int rateMin = Tools.getInteger(fdFollowConfigQf.getGapMin());
        int randomGap = (int)(Math.random()*(rateMax-rateMin+1)+rateMin);
        fdTemplateData.setGap(randomGap);
        int msgType = Tools.getInteger(replyInfo.getType()).intValue();
        if(msgType == MessageTypeEnum.MT_TEXT.getValue().intValue()){//文本
            fdTemplateData.setContent(replyInfo.getReply());
        }else if(msgType == MessageTypeEnum.MT_IMAGE.getValue().intValue()){//普通图片
            fdTemplateData.setImgUrl(replyInfo.getReply());
            fdTemplateData.setImgType(1);
        }else if(msgType == MessageTypeEnum.MT_VIDEO.getValue().intValue()){ //视频
            fdTemplateData.setVideoUrl(replyInfo.getReply());
        }else if(msgType == MessageTypeEnum.MT_GIF_IMAGE.getValue().intValue()){ //gif图片
            fdTemplateData.setImgUrl(replyInfo.getReply());
            fdTemplateData.setImgType(2);
        }else{
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    fdFollowConfigQf.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "气氛组跟发消息类型不支持此种类型，type=" +msgType)));
            return;
        }

        fdTemplateDataList.add(fdTemplateData);
        if(fdTemplateDataList == null || fdTemplateDataList.size() == 0){
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_QF_VALUE,
                    fdFollowConfigQf.getMerId(), device.getRecvmsgType(), followQfMsgDto.getDeviceUniqueId(),
                    "",0L,
                    "气氛组跟发消息内容为空！")));
            return;
        }

        //主任务
        int now = DateUtil.getNowTime();
        FdSendJob fdSendJob_parent = new FdSendJob();
        fdSendJob_parent.setId(IdWorker.getId());
        fdSendJob_parent.setParentId(0L);
        fdSendJob_parent.setMerId(fdFollowConfigQf.getMerId());
        fdSendJob_parent.setName("自动跟发(气氛组)");
        fdSendJob_parent.setSource(3);//自动跟发(气氛组)
        fdSendJob_parent.setFdDevicePlanId(followQfMsgDto.getFdFollowConfigQfId()); //气氛组跟发，此字段保存气氛组跟发的配置方案
        fdSendJob_parent.setStatus(0); //未开始
        fdSendJob_parent.setData(JSONObject.toJSONString(fdTemplateDataList));
        fdSendJob_parent.setTotalCount(0);
        fdSendJob_parent.setFinishCount(0);
        fdSendJob_parent.setFinishCountSnapshot(0);
        fdSendJob_parent.setBeginTime(now);
        fdSendJob_parent.setExptime(now + 7 * 24 * 3600);
        fdSendJob_parent.setCreateTime(now);
        fdSendJob_parent.setUpdateTime(now);
        fdSendJob_parent.setBeginTime(now);
        fdSendJob_parent.setSendStartTime(now);
        fdSendJobMapper.insertSelective(fdSendJob_parent);

        //封装子任务
        List<FdSendJob> fdSendJobList_sub = new ArrayList<>();
        FdSendJob fdSendJob_sub = new FdSendJob();
        fdSendJob_sub.setId(IdWorker.getId());
        fdSendJob_sub.setParentId(fdSendJob_parent.getId());
        fdSendJob_sub.setMerId(fdSendJob_parent.getMerId());
        fdSendJob_sub.setName(fdSendJob_parent.getName());
        fdSendJob_sub.setSource(fdSendJob_parent.getSource());
        fdSendJob_sub.setFdDevicePlanId(fdSendJob_parent.getFdDevicePlanId());
        fdSendJob_sub.setStatus(0); //未开始
        fdSendJob_sub.setData(fdSendJob_parent.getData());
        fdSendJob_sub.setTotalCount(0);
        fdSendJob_sub.setFinishCount(0);
        fdSendJob_sub.setFinishCountSnapshot(0);
        fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
        fdSendJob_sub.setExptime(fdSendJob_parent.getBeginTime() + 15 * 24 * 3600);
        fdSendJob_sub.setCreateTime(now);
        fdSendJob_sub.setUpdateTime(now);
        fdSendJob_sub.setBeginTime(fdSendJob_parent.getBeginTime());
        fdSendJob_sub.setSendStartTime(fdSendJob_parent.getBeginTime());
        //群发机器人消息
        fdSendJob_sub.setDeviceType(deviceTypeEnum.getKey());
        fdSendJob_sub.setGroupId(fdFollowConfigQfGroupTuo.getGroupWxid());
        fdSendJob_sub.setNick(fdFollowConfigQfGroup.getGroupNick());
        fdSendJob_sub.setDeviceUniqueId(fdFollowConfigQfGroup.getDeviceUniqueId());
        fdSendJob_sub.setDeviceId(fdFollowConfigQfGroup.getDeviceId());
        fdSendJob_sub.setWxid(fdFollowConfigQfGroup.getGroupWxid());
        fdSendJob_sub.setGroupSendDeviceUniqueId(fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId());
        fdSendJobList_sub.add(fdSendJob_sub);

        fdSendJobSyncService.followQfFdSendJobTaskSync(fdTemplateDataList, fdSendJobList_sub, fdFollowConfigQfGroup, fdFollowConfigQfGroupTuo);
    }


}
